package com.lanju.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.lanju.common.Contants;
import com.lanju.model.ResultModel;

/**
 * 图片操作
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("/imageOpt")
public class ImageOptController {
    
    @Value("#{configProperties['IMGURL']}")
    protected String IMGURL;
    
    private static final Logger LOGGER = LoggerFactory
            .getLogger(ImageOptController.class);
	
    /**
     * 图片文件上传
     */
    @ResponseBody
    @RequestMapping(value = "/photoUpload",method = RequestMethod.POST)
    public ResultModel photoUpload(MultipartFile file,HttpServletRequest request,HttpServletResponse response){
        if (file!=null) {// 判断上传的文件是否为空
            String path=null;// 文件路径
            String type=null;// 文件类型
            String fileName=file.getOriginalFilename();// 文件原名称
            /*System.out.println("上传的文件原名称:"+fileName);*/
            // 判断文件类型
            type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
            if (type!=null) {// 判断文件类型是否为空
                if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    /*String realPath=request.getSession().getServletContext().getRealPath("/");*/
                    String realPath = IMGURL;
                    // 自定义的文件名称
                    String trueFileName=String.valueOf(System.currentTimeMillis())+fileName;
                    // 设置存放图片文件的路径
                    path=realPath+/*System.getProperty("file.separator")+*/trueFileName;
                    /*System.out.println("存放图片文件的路径:"+path);*/
                    // 转存文件到指定的路径
                    try {
                        file.transferTo(new File(path));
                        return ResultModel.success("文件成功上传到指定目录下", trueFileName);
                    } catch (IllegalStateException | IOException e) {
                        LOGGER.error("file.transferTo fail",e);
                    }
                    return ResultModel.fail("转存失败", null);
                }else {
                    return ResultModel.fail("不是我们想要的文件类型,请按要求重新上传", null);
                }
            }else {
                return ResultModel.fail("文件类型为空", null);
            }
        }else {
            return ResultModel.fail("没有找到相对应的文件", null);
        }
    }
    /**
     * 多文件上传
     * 作者：zengqd
     * @param file
     * @return
     */
    public static List<String> mutiPicUpload(MultipartFile[] file){
    	List<String> list=new ArrayList();
		String fileTypeStr = "";
		OutputStream os = null;
		InputStream in = null;
		if (file != null && file.length > 0) {
			for (int i = 0; i < file.length; i++) {
				MultipartFile file1 = file[i];
				try {
					in = file1.getInputStream();
					byte[] bs = new byte[1024];
					int len;
					File tempFile = new File(Contants.UPLOADFILE);
					if (!tempFile.exists()) {
						tempFile.mkdirs();
					} else {
						LOGGER.info("文件夹已存在");
					}
					String filename=UUID.randomUUID().toString()+".jpg";
					String fullPath = Contants.UPLOADFILE+"/"+ filename;
					String vmURL = Contants.DATABASEFILEURL+"/"+ filename;
					String[] fullPathArr = fullPath.split("\\.");
					fileTypeStr += fullPathArr[fullPathArr.length - 1] + ",";
					os = new FileOutputStream(fullPath);
					while ((len = in.read(bs)) != -1) {
						os.write(bs, 0, len);
					}
					os.close();
					in.close();
					list.add(vmURL);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return list;
    }
    /**
     * 单文件上传
     * 作者：zengqd
     * @param file
     * @return
     */
    public static String onePicUpload(MultipartFile file){
    	List<String> list=new ArrayList();
		OutputStream os = null;
		InputStream in = null;
		if (file != null) {
			MultipartFile file1 = file;
			try {
				in = file1.getInputStream();
				byte[] bs = new byte[1024];
				int len;
				File tempFile = new File(Contants.UPLOADFILE);
				if (!tempFile.exists()) {
					tempFile.mkdirs();
				} else {
					LOGGER.info("文件夹已存在");
				}
				String filename=UUID.randomUUID().toString()+".jpg";
				String fullPath = Contants.UPLOADFILE+ "/"+filename;
				String vmURL = Contants.DATABASEFILEURL+"/"+ filename;
				os = new FileOutputStream(fullPath);
				while ((len = in.read(bs)) != -1) {
					os.write(bs, 0, len);
				}
				os.close();
				in.close();
				return vmURL;
			} catch (IOException e) {
				e.printStackTrace();
				
			}
		}
		return null;
    }
    
    
	public static String filesUpload( MultipartFile files,  String dectory) {
		MultipartFile file = files;
		String vmURL=null;
		try {
			
			 OutputStream os = null;
			 InputStream in= null;
			 String picPath=null;
			in=file.getInputStream();
	        byte[] bs = new byte[1024];
	        int len;
	        File tempFile = new File("/webapp/lanjufile/"+dectory);//linux
	//        File tempFile = new File("D:/upFiles/household");
	        if (!tempFile.exists()) {
	            tempFile.mkdirs();
	        }else{
	        	System.out.println("文件已存在");
	        }
	//        String fullPath="D:/upFiles/household/"+file.getOriginalFilename();
	        String fullPath="/webapp/lanjufile/"+dectory+"/"+file.getOriginalFilename();//linux
	        vmURL="/dataResourceImages/"+dectory+"/"+file.getOriginalFilename();
	        System.out.println("文件全路径"+fullPath);
	        String[] fullPathArr=fullPath.split("\\.");
	        os = new FileOutputStream(fullPath);
	        // 开始读取
	        while ((len = in.read(bs)) != -1) {
	            os.write(bs, 0, len);
	        } 
	        os.close();
	        in.close();
	     // 保存文件
		} catch (IOException e) {
			e.printStackTrace();
		}
			return vmURL;
		}
		
}
